<template>
  <div class="good-deeds-page">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-wrapper">
      <a-breadcrumb>
        <a-breadcrumb-item>
          <a @click="goBack">因果业力系统</a>
        </a-breadcrumb-item>
        <a-breadcrumb-item>善行记录管理</a-breadcrumb-item>
      </a-breadcrumb>
      <a-button type="text" @click="goBack" class="back-button">
        <LeftOutlined />
        返回上级
      </a-button>
    </div>

    <!-- 页面标题 -->
    <div class="ancient-title">善行记录管理</div>

    <!-- 统计概览 -->
    <a-row :gutter="[24, 24]" class="stats-row">
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic title="善行总数" :value="goodDeedsData.length" :value-style="{ color: '#52c41a', fontSize: '24px' }" suffix="条" />
        </a-card>
      </a-col>
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic title="积德总分" :value="totalGoodScore" :value-style="{ color: '#1890ff', fontSize: '24px' }" suffix="分" />
        </a-card>
      </a-col>
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic title="受益人总数" :value="totalBeneficiaries" :value-style="{ color: '#722ed1', fontSize: '24px' }" suffix="人" />
        </a-card>
      </a-col>
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic title="本月新增" :value="thisMonthCount" :value-style="{ color: '#fa8c16', fontSize: '24px' }" suffix="条" />
        </a-card>
      </a-col>
    </a-row>

    <!-- 分类统计图表 -->
    <a-row :gutter="[24, 24]" class="charts-row">
      <a-col :xs="24" :lg="12">
        <a-card title="善行类型分布" :bordered="false" class="chart-card">
          <div ref="categoryChart" style="height: 300px"></div>
        </a-card>
      </a-col>
      <a-col :xs="24" :lg="12">
        <a-card title="月度善行趋势" :bordered="false" class="chart-card">
          <div ref="trendChart" style="height: 300px"></div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 操作栏 -->
    <a-card :bordered="false" class="action-card">
      <a-row :gutter="[16, 16]" align="middle">
        <a-col :xs="24" :sm="8">
          <a-input-search v-model:value="searchQuery" placeholder="搜索人员姓名或描述" @search="handleSearch" />
        </a-col>
        <a-col :xs="24" :sm="6">
          <a-select v-model:value="categoryFilter" placeholder="善行类型筛选" @change="handleFilterChange">
            <a-select-option value="all">全部类型</a-select-option>
            <a-select-option v-for="category in goodDeedCategories" :key="category" :value="category">
              {{ category }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :xs="24" :sm="5">
          <a-button type="primary" @click="showAddModal = true">
            <PlusOutlined />
            记录善行
          </a-button>
        </a-col>
        <a-col :xs="24" :sm="5">
          <a-button @click="scrollToStatistics">
            <BarChartOutlined />
            查看统计
          </a-button>
        </a-col>
      </a-row>
    </a-card>

    <!-- 善行记录列表 -->
    <a-card title="善行记录列表" :bordered="false" class="records-card">
      <a-table :columns="columns" :data-source="filteredGoodDeeds" :loading="loading" row-key="id" :pagination="{ pageSize: 10, showSizeChanger: true, showQuickJumper: true }">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-tag :color="getActionColor(record.karmaCategory)">
              {{ karmaStore.karmaRules.goodDeeds[record.action]?.name }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'category'">
            <a-tag color="green">{{ record.karmaCategory }}</a-tag>
          </template>

          <template v-else-if="column.key === 'score'">
            <span class="score-positive">+{{ record.score }}</span>
          </template>

          <template v-else-if="column.key === 'beneficiaries'">
            <a-tooltip>
              <template #title>
                <div v-for="beneficiary in record.beneficiaries" :key="beneficiary">
                  {{ beneficiary }}
                </div>
              </template>
              <a-tag color="blue">{{ record.beneficiaries?.length || 0 }}人</a-tag>
            </a-tooltip>
          </template>

          <template v-else-if="column.key === 'verified'">
            <a-tag :color="record.verified ? 'green' : 'orange'">
              {{ record.verified ? '已验证' : '待验证' }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'actions'">
            <a-space>
              <a-button type="link" size="small" @click="viewRecord(record)"> 查看详情 </a-button>
              <a-button type="link" size="small" @click="editRecord(record)"> 编辑 </a-button>
              <a-button type="link" size="small" @click="evaluateImpact(record)"> 影响评估 </a-button>
              <a-button type="link" size="small" danger @click="deleteRecord(record)"> 删除 </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加/编辑善行记录弹窗 -->
    <a-modal v-model:open="showAddModal" :title="editingRecord ? '编辑善行记录' : '记录善行'" width="800px" @ok="handleSaveRecord" @cancel="handleCancelEdit">
      <a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="人员姓名" name="personName">
              <a-input v-model:value="formData.personName" placeholder="请输入人员姓名" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="善行类型" name="action">
              <a-select v-model:value="formData.action" placeholder="请选择善行类型">
                <a-select-opt-group v-for="(actions, category) in goodDeedsByCategory" :key="category" :label="category">
                  <a-select-option v-for="(rule, key) in actions" :key="key" :value="key"> {{ rule.name }} (+{{ rule.score }}分) </a-select-option>
                </a-select-opt-group>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="善行描述" name="description">
          <a-textarea v-model:value="formData.description" placeholder="请详细描述该善行" :rows="3" />
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="发生日期" name="date">
              <a-date-picker v-model:value="formData.date" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="发生时间" name="time">
              <a-time-picker v-model:value="formData.time" style="width: 100%" format="HH:mm" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="发生地点" name="location">
          <a-input v-model:value="formData.location" placeholder="请输入详细地点" />
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="见证人" name="witnesses">
              <a-select v-model:value="formData.witnesses" mode="tags" placeholder="请输入见证人姓名" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="受益人" name="beneficiaries">
              <a-select v-model:value="formData.beneficiaries" mode="tags" placeholder="请输入受益人信息" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="善行影响" name="impact">
          <a-textarea v-model:value="formData.impact" placeholder="请描述这个善行产生的积极影响" :rows="2" />
        </a-form-item>

        <a-form-item label="证据材料" name="evidence">
          <a-select v-model:value="formData.evidence" mode="tags" placeholder="请输入证据材料（如：照片、视频、证书等）" style="width: 100%" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 详细统计区域 -->
    <div ref="statisticsSection" class="statistics-section">
      <div class="ancient-title">善行详细统计</div>

      <!-- 影响评估概览 -->
      <a-row :gutter="[24, 24]" class="impact-overview">
        <a-col :xs="24" :lg="8">
          <a-card class="impact-card">
            <a-statistic title="总受益人数" :value="totalBeneficiaries" :value-style="{ color: '#52c41a', fontSize: '28px' }" suffix="人" />
            <div class="impact-description">善行惠及的人员总数</div>
          </a-card>
        </a-col>
        <a-col :xs="24" :lg="8">
          <a-card class="impact-card">
            <a-statistic title="社会影响力" :value="socialImpactScore" :value-style="{ color: '#1890ff', fontSize: '28px' }" suffix="分" />
            <div class="impact-description">对社会产生的积极影响</div>
          </a-card>
        </a-col>
        <a-col :xs="24" :lg="8">
          <a-card class="impact-card">
            <a-statistic title="道德提升度" :value="moralityScore" :value-style="{ color: '#722ed1', fontSize: '28px' }" suffix="分" />
            <div class="impact-description">道德品质的提升程度</div>
          </a-card>
        </a-col>
      </a-row>

      <!-- 详细统计表格 -->
      <a-row :gutter="[24, 24]" class="statistics-tables">
        <a-col :xs="24" :lg="12">
          <a-card title="善行类型统计" :bordered="false" class="stats-table-card">
            <a-table :columns="categoryStatsColumns" :data-source="categoryStatistics" :pagination="false" size="small" :scroll="{ y: 400 }" />
          </a-card>
        </a-col>
        <a-col :xs="24" :lg="12">
          <a-card title="个人善行排行" :bordered="false" class="stats-table-card">
            <a-table :columns="personStatsColumns" :data-source="personStatistics" :pagination="{ pageSize: 8, size: 'small' }" size="small" :scroll="{ y: 400 }" />
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 影响评估弹窗 -->
    <a-modal v-model:open="showImpactModal" title="善行影响评估" width="600px" @ok="saveImpactAssessment">
      <div v-if="currentRecord">
        <a-descriptions title="善行基本信息" :column="2" size="small">
          <a-descriptions-item label="人员">{{ currentRecord.personName }}</a-descriptions-item>
          <a-descriptions-item label="善行">{{ karmaStore.karmaRules.goodDeeds[currentRecord.action]?.name }}</a-descriptions-item>
          <a-descriptions-item label="时间">{{ currentRecord.date }}</a-descriptions-item>
          <a-descriptions-item label="地点">{{ currentRecord.location }}</a-descriptions-item>
        </a-descriptions>

        <a-divider />

        <a-form layout="vertical">
          <a-form-item label="影响范围评分 (1-10分)">
            <a-slider v-model:value="impactAssessment.scope" :min="1" :max="10" :marks="{ 1: '个人', 5: '社区', 10: '社会' }" />
          </a-form-item>

          <a-form-item label="持续时间评分 (1-10分)">
            <a-slider v-model:value="impactAssessment.duration" :min="1" :max="10" :marks="{ 1: '短期', 5: '中期', 10: '长期' }" />
          </a-form-item>

          <a-form-item label="积极程度评分 (1-10分)">
            <a-slider v-model:value="impactAssessment.positivity" :min="1" :max="10" :marks="{ 1: '轻微', 5: '显著', 10: '重大' }" />
          </a-form-item>

          <a-form-item label="道德示范评分 (1-10分)">
            <a-slider v-model:value="impactAssessment.morality" :min="1" :max="10" :marks="{ 1: '一般', 5: '良好', 10: '卓越' }" />
          </a-form-item>

          <a-form-item label="评估说明">
            <a-textarea v-model:value="impactAssessment.notes" placeholder="请描述具体的影响和意义" :rows="3" />
          </a-form-item>
        </a-form>

        <a-alert :message="`综合影响评分: ${impactAssessment.totalScore}分`" :type="getImpactLevel(impactAssessment.totalScore).type" :description="getImpactLevel(impactAssessment.totalScore).description" show-icon />
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, reactive, watch, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, BarChartOutlined, LeftOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import { useKarmaStore } from '@/stores'
import dayjs from 'dayjs'
import * as echarts from 'echarts'

// 状态管理
const karmaStore = useKarmaStore()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const showAddModal = ref(false)
const showImpactModal = ref(false)
const editingRecord = ref(null)
const currentRecord = ref(null)
const formRef = ref()
const searchQuery = ref('')
const categoryFilter = ref('all')
const categoryChart = ref()
const trendChart = ref()
const statisticsSection = ref()
const categoryChartInstance = ref(null)
const trendChartInstance = ref(null)

// 表单数据
const formData = reactive({
  personName: '',
  action: '',
  description: '',
  date: null,
  time: null,
  location: '',
  witnesses: [],
  beneficiaries: [],
  impact: '',
  evidence: []
})

// 影响评估数据
const impactAssessment = reactive({
  scope: 5,
  duration: 5,
  positivity: 5,
  morality: 5,
  notes: '',
  totalScore: computed(() => {
    return (((impactAssessment.scope + impactAssessment.duration + impactAssessment.positivity + impactAssessment.morality) / 4) * 10).toFixed(1)
  })
})

// 表单验证规则
const formRules = {
  personName: [{ required: true, message: '请输入人员姓名', trigger: 'blur' }],
  action: [{ required: true, message: '请选择善行类型', trigger: 'change' }],
  description: [{ required: true, message: '请输入善行描述', trigger: 'blur' }],
  location: [{ required: true, message: '请输入发生地点', trigger: 'blur' }]
}

// 获取善行数据
const goodDeedsData = computed(() => {
  return karmaStore.karmaRecords.filter((record) => record.score > 0)
})

// 过滤后的善行数据
const filteredGoodDeeds = computed(() => {
  let result = goodDeedsData.value

  if (searchQuery.value) {
    result = result.filter((record) => record.personName.includes(searchQuery.value) || record.description.includes(searchQuery.value))
  }

  if (categoryFilter.value !== 'all') {
    result = result.filter((record) => record.karmaCategory === categoryFilter.value)
  }

  return result
})

// 善行类型分类
const goodDeedCategories = computed(() => {
  const categories = new Set()
  Object.values(karmaStore.karmaRules.goodDeeds).forEach((rule) => {
    categories.add(rule.category)
  })
  return Array.from(categories)
})

// 按类别分组的善行
const goodDeedsByCategory = computed(() => {
  const grouped = {}
  Object.entries(karmaStore.karmaRules.goodDeeds).forEach(([key, rule]) => {
    if (!grouped[rule.category]) {
      grouped[rule.category] = {}
    }
    grouped[rule.category][key] = rule
  })
  return grouped
})

// 统计数据
const totalGoodScore = computed(() => goodDeedsData.value.reduce((sum, record) => sum + record.score, 0))

const totalBeneficiaries = computed(() => {
  const beneficiaries = new Set()
  goodDeedsData.value.forEach((record) => {
    record.beneficiaries?.forEach((beneficiary) => beneficiaries.add(beneficiary))
  })
  return beneficiaries.size
})

const thisMonthCount = computed(() => {
  const thisMonth = dayjs().format('YYYY-MM')
  return goodDeedsData.value.filter((record) => record.date.startsWith(thisMonth)).length
})

// 类型统计
const categoryStatistics = computed(() => {
  const stats = {}
  goodDeedsData.value.forEach((record) => {
    const category = record.karmaCategory
    if (!stats[category]) {
      stats[category] = {
        category,
        count: 0,
        totalScore: 0,
        avgScore: 0,
        beneficiaries: new Set()
      }
    }
    stats[category].count++
    stats[category].totalScore += record.score
    record.beneficiaries?.forEach((b) => stats[category].beneficiaries.add(b))
  })

  return Object.values(stats).map((stat) => ({
    ...stat,
    avgScore: (stat.totalScore / stat.count).toFixed(1),
    beneficiariesCount: stat.beneficiaries.size,
    beneficiaries: undefined // 移除Set对象
  }))
})

// 个人统计
const personStatistics = computed(() => {
  const stats = {}
  goodDeedsData.value.forEach((record) => {
    if (!stats[record.personName]) {
      stats[record.personName] = {
        personName: record.personName,
        count: 0,
        totalScore: 0,
        categories: new Set(),
        beneficiaries: new Set()
      }
    }
    stats[record.personName].count++
    stats[record.personName].totalScore += record.score
    stats[record.personName].categories.add(record.karmaCategory)
    record.beneficiaries?.forEach((b) => stats[record.personName].beneficiaries.add(b))
  })

  return Object.values(stats)
    .map((stat) => ({
      ...stat,
      avgScore: (stat.totalScore / stat.count).toFixed(1),
      categoriesCount: stat.categories.size,
      beneficiariesCount: stat.beneficiaries.size,
      categories: undefined,
      beneficiaries: undefined
    }))
    .sort((a, b) => b.totalScore - a.totalScore)
})

// 社会影响力评分
const socialImpactScore = computed(() => {
  return Math.round(totalBeneficiaries.value * 0.8 + totalGoodScore.value * 0.2)
})

// 道德提升度评分
const moralityScore = computed(() => {
  const highMoralityActions = goodDeedsData.value.filter((record) => ['救助生命', '孝道仁义'].includes(record.karmaCategory)).length
  return Math.round(highMoralityActions * 10 + goodDeedsData.value.length * 2)
})

// 表格列配置
const columns = [
  { title: '人员姓名', dataIndex: 'personName', key: 'personName', width: 100 },
  { title: '善行类型', key: 'action', width: 120 },
  { title: '类别', key: 'category', width: 100 },
  { title: '积分', key: 'score', width: 80, align: 'center' },
  { title: '日期', dataIndex: 'date', key: 'date', width: 100 },
  { title: '地点', dataIndex: 'location', key: 'location', width: 150, ellipsis: true },
  { title: '受益人', key: 'beneficiaries', width: 80, align: 'center' },
  { title: '验证状态', key: 'verified', width: 100, align: 'center' },
  { title: '操作', key: 'actions', width: 200, fixed: 'right' }
]

// 类型统计表格列
const categoryStatsColumns = [
  { title: '善行类型', dataIndex: 'category', key: 'category' },
  { title: '记录数量', dataIndex: 'count', key: 'count', align: 'center' },
  { title: '总积分', dataIndex: 'totalScore', key: 'totalScore', align: 'center' },
  { title: '平均积分', dataIndex: 'avgScore', key: 'avgScore', align: 'center' },
  { title: '受益人数', dataIndex: 'beneficiariesCount', key: 'beneficiariesCount', align: 'center' }
]

// 个人统计表格列
const personStatsColumns = [
  { title: '人员姓名', dataIndex: 'personName', key: 'personName' },
  { title: '善行次数', dataIndex: 'count', key: 'count', align: 'center' },
  { title: '总积分', dataIndex: 'totalScore', key: 'totalScore', align: 'center' },
  { title: '平均积分', dataIndex: 'avgScore', key: 'avgScore', align: 'center' },
  { title: '涉及类型', dataIndex: 'categoriesCount', key: 'categoriesCount', align: 'center' },
  { title: '受益人数', dataIndex: 'beneficiariesCount', key: 'beneficiariesCount', align: 'center' }
]

// 方法
const getActionColor = (category) => {
  const colors = {
    慈善救助: 'blue',
    救助生命: 'red',
    社会服务: 'green',
    孝道仁义: 'purple',
    环境保护: 'cyan'
  }
  return colors[category] || 'blue'
}

const getImpactLevel = (score) => {
  if (score >= 80) return { type: 'success', description: '影响深远，意义重大' }
  if (score >= 60) return { type: 'info', description: '积极影响，值得肯定' }
  if (score >= 40) return { type: 'warning', description: '有一定影响，可以改进' }
  return { type: 'error', description: '影响有限，需要加强' }
}

const handleSearch = () => {
  // 搜索逻辑已在computed中处理
}

const handleFilterChange = () => {
  // 过滤逻辑已在computed中处理
}

const viewRecord = (record) => {
  currentRecord.value = record
  // 可以显示详情弹窗
  message.info('查看详情功能')
}

const editRecord = (record) => {
  editingRecord.value = record
  Object.assign(formData, {
    ...record,
    date: record.date ? dayjs(record.date) : null,
    time: record.time ? dayjs(record.time, 'HH:mm') : null
  })
  showAddModal.value = true
}

const evaluateImpact = (record) => {
  currentRecord.value = record
  // 重置评估数据
  impactAssessment.scope = 5
  impactAssessment.duration = 5
  impactAssessment.positivity = 5
  impactAssessment.morality = 5
  impactAssessment.notes = ''
  showImpactModal.value = true
}

const deleteRecord = async (record) => {
  try {
    const result = await karmaStore.deleteKarmaRecord(record.id)
    if (result.success) {
      message.success('删除成功')
    } else {
      message.error(result.error)
    }
  } catch (error) {
    message.error('删除失败')
  }
}

const handleSaveRecord = async () => {
  try {
    await formRef.value.validate()

    const recordData = {
      ...formData,
      type: 'goodDeed',
      date: formData.date ? formData.date.format('YYYY-MM-DD') : null,
      time: formData.time ? formData.time.format('HH:mm') : null
    }

    console.log('保存记录数据:', recordData)

    let result
    if (editingRecord.value) {
      result = await karmaStore.updateKarmaRecord(editingRecord.value.id, recordData)
    } else {
      result = await karmaStore.addKarmaRecord(recordData)
    }

    if (result.success) {
      message.success(editingRecord.value ? '更新成功' : '添加成功')
      showAddModal.value = false
      handleCancelEdit()
      // 手动触发数据重新计算
      console.log('记录保存成功，重新计算图表数据')
    } else {
      message.error(result.error)
    }
  } catch (error) {
    console.error('保存失败:', error)
  }
}

const handleCancelEdit = () => {
  editingRecord.value = null
  formRef.value?.resetFields()
  Object.assign(formData, {
    personName: '',
    action: '',
    description: '',
    date: null,
    time: null,
    location: '',
    witnesses: [],
    beneficiaries: [],
    impact: '',
    evidence: []
  })
}

const saveImpactAssessment = () => {
  // 保存影响评估结果
  message.success(`影响评估已保存，综合评分: ${impactAssessment.totalScore}分`)
  showImpactModal.value = false
}

// 返回上级页面
const goBack = () => {
  router.push('/karma')
}

// 滚动到统计区域
const scrollToStatistics = () => {
  if (statisticsSection.value) {
    statisticsSection.value.scrollIntoView({
      behavior: 'smooth',
      block: 'start'
    })
  }
}

// 图表数据计算
const categoryChartData = computed(() => {
  const stats = {}
  goodDeedsData.value.forEach((record) => {
    const category = record.karmaCategory
    if (!stats[category]) {
      stats[category] = { count: 0, score: 0 }
    }
    stats[category].count++
    stats[category].score += record.score
  })

  return Object.entries(stats).map(([name, data]) => ({
    name,
    value: data.count,
    score: data.score
  }))
})

const trendChartData = computed(() => {
  // 添加详细调试
  const allRecords = karmaStore.karmaRecords
  const goodRecords = allRecords.filter((record) => record.score > 0)

  const monthStats = {}
  goodRecords.forEach((record) => {
    const month = dayjs(record.date).format('YYYY-MM')
    if (!monthStats[month]) {
      monthStats[month] = { count: 0, score: 0, avgScore: 0, categories: new Set() }
    }
    monthStats[month].count++
    monthStats[month].score += record.score
    monthStats[month].categories.add(record.karmaCategory)
  })

  // 计算平均分
  Object.keys(monthStats).forEach((month) => {
    monthStats[month].avgScore = monthStats[month].count > 0 ? monthStats[month].score / monthStats[month].count : 0
    monthStats[month].categoryCount = monthStats[month].categories.size
  })

  // 获取最近12个月的数据，增加数据量
  const months = []
  const counts = []
  const scores = []
  const avgScores = []
  const categoryCount = []

  for (let i = 11; i >= 0; i--) {
    const month = dayjs().subtract(i, 'month').format('YYYY-MM')
    const monthName = dayjs().subtract(i, 'month').format('MM月')
    months.push(monthName)
    counts.push(monthStats[month]?.count || 0)
    scores.push(monthStats[month]?.score || 0)
    avgScores.push(parseFloat((monthStats[month]?.avgScore || 0).toFixed(1)))
    categoryCount.push(monthStats[month]?.categoryCount || 0)
  }

  return { months, counts, scores, avgScores, categoryCount }
})

// 初始化类型分布图表
const initCategoryChart = () => {
  if (!categoryChart.value) return

  // 销毁旧的图表实例
  if (categoryChartInstance.value) {
    categoryChartInstance.value.dispose()
    categoryChartInstance.value = null
  }

  const chart = echarts.init(categoryChart.value)
  categoryChartInstance.value = chart

  // 定义渐变色彩方案
  const colors = [
    {
      type: 'radial',
      x: 0.3,
      y: 0.3,
      r: 0.8,
      colorStops: [
        { offset: 0, color: '#ff6b6b' },
        { offset: 1, color: '#ee5a52' }
      ]
    },
    {
      type: 'radial',
      x: 0.3,
      y: 0.3,
      r: 0.8,
      colorStops: [
        { offset: 0, color: '#4ecdc4' },
        { offset: 1, color: '#26d0ce' }
      ]
    },
    {
      type: 'radial',
      x: 0.3,
      y: 0.3,
      r: 0.8,
      colorStops: [
        { offset: 0, color: '#45b7d1' },
        { offset: 1, color: '#2196f3' }
      ]
    },
    {
      type: 'radial',
      x: 0.3,
      y: 0.3,
      r: 0.8,
      colorStops: [
        { offset: 0, color: '#f9ca24' },
        { offset: 1, color: '#f0932b' }
      ]
    },
    {
      type: 'radial',
      x: 0.3,
      y: 0.3,
      r: 0.8,
      colorStops: [
        { offset: 0, color: '#6c5ce7' },
        { offset: 1, color: '#5f3dc4' }
      ]
    }
  ]

  // 处理数据并添加颜色
  const chartData = categoryChartData.value.map((item, index) => ({
    ...item,
    itemStyle: {
      color: colors[index % colors.length],
      shadowBlur: 20,
      shadowColor: 'rgba(0, 0, 0, 0.3)'
    }
  }))

  const option = {
    backgroundColor: 'transparent',
    title: {
      text: '善行类型分布',
      subtext: `总计 ${chartData.reduce((sum, item) => sum + item.value, 0)} 次善行`,
      left: 'center',
      top: '5%',
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#fff',
        textShadowColor: 'rgba(114, 46, 209, 0.5)',
        textShadowBlur: 10,
        textShadowOffsetX: 2,
        textShadowOffsetY: 2
      },
      subtextStyle: {
        color: '#d4991a',
        fontSize: 12
      }
    },
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: '#722ed1',
      borderWidth: 1,
      textStyle: {
        color: '#fff'
      },
      formatter: function (params) {
        return `
          <div style="padding: 10px;">
            <div style="font-size: 14px; font-weight: bold; margin-bottom: 5px;">${params.name}</div>
            <div style="margin-bottom: 3px;">善行次数: <span style="color: #52c41a;">${params.value}</span></div>
            <div style="margin-bottom: 3px;">占比: <span style="color: #1890ff;">${params.percent}%</span></div>
            <div>总积分: <span style="color: #f0932b;">${params.data.score || 0}</span></div>
          </div>
        `
      }
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: '5%',
      top: 'center',
      backgroundColor: 'rgba(255, 255, 255, 0.05)',
      borderColor: 'rgba(255, 255, 255, 0.2)',
      borderWidth: 1,
      borderRadius: 8,
      padding: [15, 20],
      textStyle: {
        color: '#fff',
        fontSize: 12
      },
      pageIconColor: '#722ed1',
      pageIconInactiveColor: '#666',
      pageTextStyle: {
        color: '#fff'
      }
    },
    series: [
      {
        name: '善行类型',
        type: 'pie',
        radius: ['30%', '60%'],
        center: ['40%', '55%'],
        data: chartData,
        roseType: 'area',
        animationType: 'scale',
        animationEasing: 'elasticOut',
        animationDelay: function (idx) {
          return Math.random() * 200
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}\n{c}次',
          color: '#fff',
          fontSize: 11,
          fontWeight: 'bold'
        },
        labelLine: {
          show: true,
          length: 15,
          length2: 8,
          lineStyle: {
            color: '#fff',
            width: 1
          }
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 30,
            shadowOffsetX: 0,
            shadowOffsetY: 0,
            shadowColor: 'rgba(114, 46, 209, 0.8)'
          },
          label: {
            fontSize: 14,
            fontWeight: 'bold'
          }
        }
      }
    ]
  }

  chart.setOption(option, true)

  // 添加点击事件
  chart.on('click', function (params) {
    console.log('点击了善行类型:', params.name)
  })

  // 响应式调整
  const resizeHandler = () => {
    if (categoryChartInstance.value) {
      categoryChartInstance.value.resize()
    }
  }
  window.addEventListener('resize', resizeHandler)
}

// 初始化趋势图表
const initTrendChart = () => {
  if (!trendChart.value) {
    console.log('趋势图表容器未找到')
    return
  }

  // 销毁旧的图表实例
  if (trendChartInstance.value) {
    trendChartInstance.value.dispose()
    trendChartInstance.value = null
  }

  const chart = echarts.init(trendChart.value)
  trendChartInstance.value = chart

  const { months, counts, scores, avgScores, categoryCount } = trendChartData.value

  const option = {
    backgroundColor: 'transparent',
    title: {
      text: '月度善行趋势分析',
      left: 'center',
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#fff',
        textShadowColor: 'rgba(114, 46, 209, 0.5)',
        textShadowBlur: 10,
        textShadowOffsetX: 2,
        textShadowOffsetY: 2
      },
      subtextStyle: {
        color: '#d4991a',
        fontSize: 12
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 0, 0, 0.85)',
      borderColor: '#722ed1',
      borderWidth: 2,
      borderRadius: 8,
      textStyle: {
        color: '#fff',
        fontSize: 12
      },
      formatter: function (params) {
        let result = `<div style="padding: 10px; font-size: 13px;">
          <div style="font-weight: bold; margin-bottom: 8px; color: #d4991a; border-bottom: 1px solid #722ed1; padding-bottom: 5px;">${params[0].axisValue}</div>`

        params.forEach(function (item) {
          const color = item.color?.colorStops ? item.color.colorStops[0].color : item.color
          result += `<div style="margin: 4px 0; display: flex; justify-content: space-between; align-items: center;">
            <span style="display: inline-block; width: 10px; height: 10px; background: ${color}; border-radius: 50%; margin-right: 8px;"></span>
            <span style="flex: 1;">${item.seriesName}:</span>
            <span style="font-weight: bold; color: ${color}; margin-left: 10px;">${item.value}${item.seriesName.includes('次数') || item.seriesName.includes('类型') ? '个' : item.seriesName.includes('积分') ? '分' : ''}</span>
          </div>`
        })

        result += '</div>'
        return result
      },
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#722ed1',
          width: 1,
          opacity: 0.8
        },
        lineStyle: {
          color: '#722ed1',
          width: 1,
          opacity: 0.8
        }
      }
    },
    legend: {
      data: ['善行次数', '积分总数', '平均积分', '涉及类型'],
      top: '12%',
      textStyle: {
        color: '#fff',
        fontSize: 11
      },
      itemGap: 20,
      itemWidth: 14,
      itemHeight: 10
    },
    grid: {
      left: '8%',
      right: '8%',
      bottom: '12%',
      top: '25%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      axisLabel: {
        color: '#fff',
        fontSize: 11,
        rotate: 0,
        interval: 0
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)',
          width: 1
        }
      },
      axisTick: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)'
        }
      },
      splitLine: {
        show: false
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '次数/类型数',
        position: 'left',
        axisLabel: {
          color: '#fff',
          fontSize: 10
        },
        nameTextStyle: {
          color: '#fff',
          fontSize: 11
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.1)',
            type: 'dashed'
          }
        }
      },
      {
        type: 'value',
        name: '积分',
        position: 'right',
        axisLabel: {
          color: '#fff',
          fontSize: 10
        },
        nameTextStyle: {
          color: '#fff',
          fontSize: 11
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        },
        splitLine: {
          show: false
        }
      }
    ],
    series: [
      {
        name: '善行次数',
        type: 'line',
        data: counts,
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              { offset: 0, color: '#4facfe' },
              { offset: 1, color: '#00f2fe' }
            ]
          },
          shadowBlur: 10,
          shadowColor: 'rgba(79, 172, 254, 0.5)'
        },
        lineStyle: {
          width: 3,
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              { offset: 0, color: '#4facfe' },
              { offset: 1, color: '#00f2fe' }
            ]
          },
          shadowBlur: 10,
          shadowColor: 'rgba(79, 172, 254, 0.3)'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(79, 172, 254, 0.3)' },
              { offset: 1, color: 'rgba(79, 172, 254, 0.05)' }
            ]
          }
        }
      },
      {
        name: '积分总数',
        type: 'bar',
        yAxisIndex: 1,
        data: scores,
        barWidth: '30%',
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#a8edea' },
              { offset: 1, color: '#fed6e3' }
            ]
          },
          borderRadius: [4, 4, 0, 0],
          shadowBlur: 8,
          shadowColor: 'rgba(168, 237, 234, 0.4)',
          shadowOffsetY: 4
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 15,
            shadowColor: 'rgba(168, 237, 234, 0.6)'
          }
        }
      },
      {
        name: '平均积分',
        type: 'line',
        data: avgScores,
        smooth: true,
        symbol: 'diamond',
        symbolSize: 8,
        itemStyle: {
          color: {
            type: 'radial',
            x: 0.5,
            y: 0.5,
            r: 0.5,
            colorStops: [
              { offset: 0, color: '#ff9a9e' },
              { offset: 1, color: '#fecfef' }
            ]
          },
          shadowBlur: 10,
          shadowColor: 'rgba(255, 154, 158, 0.5)'
        },
        lineStyle: {
          width: 2,
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              { offset: 0, color: '#ff9a9e' },
              { offset: 1, color: '#fecfef' }
            ]
          },
          type: 'dashed'
        }
      },
      {
        name: '涉及类型',
        type: 'line',
        data: categoryCount,
        smooth: true,
        symbol: 'triangle',
        symbolSize: 7,
        itemStyle: {
          color: {
            type: 'radial',
            x: 0.5,
            y: 0.5,
            r: 0.5,
            colorStops: [
              { offset: 0, color: '#ffecd2' },
              { offset: 1, color: '#fcb69f' }
            ]
          },
          shadowBlur: 10,
          shadowColor: 'rgba(252, 182, 159, 0.5)'
        },
        lineStyle: {
          width: 2,
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              { offset: 0, color: '#ffecd2' },
              { offset: 1, color: '#fcb69f' }
            ]
          },
          type: 'dotted'
        }
      }
    ]
  }

  chart.setOption(option, true)
  console.log('趋势图表设置完成')

  // 添加点击事件
  chart.on('click', function (params) {
    console.log('点击了月度数据:', params)
  })

  // 响应式调整
  const resizeHandler = () => {
    if (trendChartInstance.value) {
      trendChartInstance.value.resize()
    }
  }
  window.addEventListener('resize', resizeHandler)
}

// 生命周期
onMounted(async () => {
  await karmaStore.fetchKarmaRecords()
  nextTick(() => {
    initCategoryChart()
    initTrendChart()
  })
})

// 监听karma store的数据变化
watch(
  () => karmaStore.karmaRecords,
  (newRecords) => {
    if (newRecords.length > 0) {
      nextTick(() => {
        console.log('重新渲染图表...')
        initCategoryChart()
        initTrendChart()
      })
    }
  },
  { deep: true, immediate: true }
)

// 组件卸载前清理资源
onBeforeUnmount(() => {
  if (categoryChartInstance.value) {
    categoryChartInstance.value.dispose()
    categoryChartInstance.value = null
  }
  if (trendChartInstance.value) {
    trendChartInstance.value.dispose()
    trendChartInstance.value = null
  }
})
</script>

<style lang="scss" scoped>
@use 'sass:color';

.good-deeds-page {
  padding: 24px;
  min-height: 100vh;

  // 面包屑导航样式 - 仿照Dashboard
  .breadcrumb-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px 20px;
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 12px;
    backdrop-filter: blur(10px);

    :deep(.ant-breadcrumb) {
      .ant-breadcrumb-link {
        color: $text-secondary;

        a {
          color: $primary-color;

          &:hover {
            color: color.adjust($primary-color, $lightness: 10%);
          }
        }
      }

      .ant-breadcrumb-separator {
        color: $text-tertiary;
      }
    }

    .back-button {
      color: $primary-color;
      border: none;
      background: transparent;

      &:hover {
        color: lighten($primary-color, 10%);
        background: rgba(114, 46, 209, 0.1);
      }
    }
  }

  // 页面标题样式 - 仿照Dashboard
  .ancient-title {
    text-align: center;
    font-size: 32px;
    font-weight: bold;
    color: $secondary-color;
    margin-bottom: 48px;
    text-shadow: 0 0 20px rgba(212, 153, 10, 0.3);
    font-family: 'PingFang SC', '微软雅黑', sans-serif;
  }

  // 统计卡片区域样式
  .stats-row,
  .charts-row {
    margin-bottom: 32px;
  }

  // 统计卡片样式 - 仿照Dashboard
  .stat-card {
    background: rgba(255, 255, 255, 0.03);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 16px;
    padding: 24px;
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(10px);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 3px;
      background: linear-gradient(90deg, transparent, #52c41a, transparent);
      opacity: 0.6;
    }

    :deep(.ant-statistic) {
      text-align: center;

      .ant-statistic-title {
        color: $text-secondary;
        font-size: 14px;
        margin-bottom: 8px;
      }

      .ant-statistic-content {
        .ant-statistic-content-value {
          color: currentColor;
          font-weight: bold;
        }
      }
    }
  }

  // 图表卡片和其他卡片样式 - 仿照Dashboard section样式
  .chart-card,
  .action-card,
  .records-card {
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 16px;
    backdrop-filter: blur(10px);

    :deep(.ant-card-head) {
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      background: transparent;

      .ant-card-head-title {
        color: $text-primary;
        font-size: 18px;
        font-weight: 600;
      }
    }

    :deep(.ant-card-body) {
      color: $text-primary;
    }
  }

  // 善行记录列表特殊处理
  .records-card {
    margin-bottom: 32px;
  }

  // 分数样式
  .score-positive {
    color: #52c41a;
    font-weight: bold;
  }

  // 详细统计区域样式
  .statistics-section {
    margin-top: 64px;
    padding: 48px 0;

    .ancient-title {
      text-align: center;
      font-size: 28px;
      font-weight: bold;
      color: $secondary-color;
      margin-bottom: 48px;
      text-shadow: 0 0 20px rgba(212, 153, 10, 0.3);
    }

    .impact-overview {
      margin-bottom: 48px;
    }

    .impact-card {
      background: rgba(255, 255, 255, 0.03);
      border: 1px solid rgba(255, 255, 255, 0.1);
      border-radius: 16px;
      padding: 32px 24px;
      height: 140px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      backdrop-filter: blur(10px);
      transition: all 0.3s ease;
      position: relative;
      overflow: hidden;

      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 3px;
        background: linear-gradient(90deg, transparent, #52c41a, transparent);
        opacity: 0.6;
      }

      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 30px rgba(114, 46, 209, 0.2);
      }

      :deep(.ant-statistic) {
        text-align: center;

        .ant-statistic-title {
          color: $text-secondary;
          font-size: 16px;
          margin-bottom: 12px;
          font-weight: 500;
        }

        .ant-statistic-content {
          .ant-statistic-content-value {
            color: currentColor;
            font-weight: bold;
          }
        }
      }

      .impact-description {
        color: $text-tertiary;
        font-size: 12px;
        margin-top: 8px;
        text-align: center;
      }
    }

    .statistics-tables {
      margin-bottom: 32px;
    }

    .stats-table-card {
      background: rgba(255, 255, 255, 0.05);
      border: 1px solid rgba(255, 255, 255, 0.15);
      border-radius: 16px;
      backdrop-filter: blur(10px);
      height: 500px;

      :deep(.ant-card-head) {
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        background: transparent;

        .ant-card-head-title {
          color: $text-primary;
          font-size: 18px;
          font-weight: 600;
        }
      }

      :deep(.ant-card-body) {
        color: $text-primary;
        padding: 16px;
        height: calc(100% - 60px);
        overflow: hidden;
      }

      :deep(.ant-table) {
        .ant-table-thead > tr > th {
          background: rgba(255, 255, 255, 0.08);
          border-bottom: 1px solid rgba(255, 255, 255, 0.1);
          color: $text-primary;
          font-weight: 600;
        }

        .ant-table-tbody > tr > td {
          background: transparent;
          border-bottom: 1px solid rgba(255, 255, 255, 0.05);
          color: $text-secondary;
        }

        .ant-table-tbody > tr:hover > td {
          background: rgba(255, 255, 255, 0.05);
        }
      }
    }
  }

  // 影响评估区域样式
  .impact-assessment {
    :deep(.ant-card) {
      background: rgba(255, 255, 255, 0.08);
      border: 1px solid rgba(255, 255, 255, 0.15);
      border-radius: 12px;
      margin-bottom: 16px;

      .ant-card-head {
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        background: transparent;

        .ant-card-head-title {
          color: $text-primary;
        }
      }

      .ant-card-body {
        color: $text-primary;
      }
    }
  }

  // 表格样式调整
  :deep(.ant-table) {
    background: transparent;

    .ant-table-container {
      background: transparent;
    }

    .ant-table-thead > tr > th {
      background: rgba(255, 255, 255, 0.08);
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      color: $text-primary;
    }

    .ant-table-tbody > tr > td {
      background: transparent;
      border-bottom: 1px solid rgba(255, 255, 255, 0.05);
      color: $text-secondary;
    }

    .ant-table-tbody > tr:hover > td {
      background: rgba(255, 255, 255, 0.05);
    }
  }

  // 标签页样式
  :deep(.ant-tabs) {
    .ant-tabs-nav {
      &::before {
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      }
    }

    .ant-tabs-tab {
      color: $text-secondary;

      &.ant-tabs-tab-active {
        color: $primary-color;
      }

      &:hover {
        color: $primary-color;
      }
    }

    .ant-tabs-ink-bar {
      background: $primary-color;
    }

    .ant-tabs-content-holder {
      .ant-tabs-content {
        color: $text-primary;
      }
    }
  }

  // 表单样式
  :deep(.ant-form) {
    .ant-form-item-label > label {
      color: $text-primary;
    }
  }

  // 输入框和选择器样式
  :deep(.ant-input),
  :deep(.ant-select-selector),
  :deep(.ant-input-number),
  :deep(.ant-picker),
  :deep(.ant-textarea) {
    background: rgba(255, 255, 255, 0.08);
    border-color: rgba(255, 255, 255, 0.2);
    color: $text-primary;

    &:hover {
      border-color: $primary-color;
    }

    &:focus {
      border-color: $primary-color;
      box-shadow: 0 0 0 2px rgba(114, 46, 209, 0.2);
    }
  }

  :deep(.ant-input::placeholder),
  :deep(.ant-textarea::placeholder) {
    color: $text-tertiary;
  }

  :deep(.ant-select) {
    .ant-select-selection-placeholder {
      color: $text-tertiary;
    }

    .ant-select-arrow {
      color: $text-secondary;
    }
  }

  // 按钮样式调整
  :deep(.ant-btn) {
    &.ant-btn-primary {
      background: $primary-color;
      border-color: $primary-color;

      &:hover {
        background: color.adjust($primary-color, $lightness: 10%);
        border-color: color.adjust($primary-color, $lightness: 10%);
      }
    }

    &.ant-btn-link {
      color: $primary-color;

      &:hover {
        color: color.adjust($primary-color, $lightness: 10%);
      }
    }

    &:not(.ant-btn-primary):not(.ant-btn-link) {
      background: rgba(255, 255, 255, 0.08);
      border-color: rgba(255, 255, 255, 0.2);
      color: $text-primary;

      &:hover {
        background: rgba(255, 255, 255, 0.15);
        border-color: $primary-color;
        color: $primary-color;
      }
    }
  }

  // 标签样式
  :deep(.ant-tag) {
    background: rgba(255, 255, 255, 0.1);
    border-color: rgba(255, 255, 255, 0.2);
    color: $text-primary;

    &[color] {
      border: none;
    }
  }

  // 进度条样式
  :deep(.ant-progress) {
    .ant-progress-text {
      color: $text-primary;
    }
  }

  // 滑块样式
  :deep(.ant-slider) {
    .ant-slider-track {
      background: $primary-color;
    }

    .ant-slider-handle {
      border-color: $primary-color;
    }

    .ant-slider-mark-text {
      color: $text-tertiary;
    }
  }

  // 警告框样式
  :deep(.ant-alert) {
    background: rgba(255, 255, 255, 0.08);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 12px;

    .ant-alert-message {
      color: $text-primary;
    }

    .ant-alert-description {
      color: $text-secondary;
    }
  }

  // 模态框样式
  :deep(.ant-modal) {
    .ant-modal-content {
      background: rgba(30, 30, 35, 0.95);
      backdrop-filter: blur(20px);
      border: 1px solid rgba(255, 255, 255, 0.15);
    }

    .ant-modal-header {
      background: transparent;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);

      .ant-modal-title {
        color: $text-primary;
      }
    }

    .ant-modal-body {
      color: $text-primary;
    }

    .ant-modal-footer {
      border-top: 1px solid rgba(255, 255, 255, 0.1);
      background: transparent;
    }
  }

  // 描述列表样式
  :deep(.ant-descriptions) {
    .ant-descriptions-header {
      .ant-descriptions-title {
        color: $text-primary;
        font-size: 16px;
        font-weight: 600;
      }
    }

    .ant-descriptions-item-label {
      color: $text-secondary;
    }

    .ant-descriptions-item-content {
      color: $text-primary;
    }
  }

  // 分割线样式
  :deep(.ant-divider) {
    border-color: rgba(255, 255, 255, 0.1);
  }

  // 时间选择器样式
  :deep(.ant-time-picker) {
    .ant-picker-input > input {
      color: $text-primary;
    }
  }

  // 日期选择器样式
  :deep(.ant-date-picker) {
    .ant-picker-input > input {
      color: $text-primary;
    }
  }
}

// 响应式适配
@media (max-width: 1200px) {
  .good-deeds-page {
    .stat-card {
      height: 100px;
      padding: 20px;
    }
  }
}

@media (max-width: 768px) {
  .good-deeds-page {
    padding: 16px;

    .stats-row,
    .charts-row {
      margin-bottom: 24px;
    }

    .stat-card {
      height: 80px;
      padding: 16px;
    }

    .breadcrumb-wrapper {
      padding: 12px 16px;
      flex-direction: column;
      gap: 12px;
      align-items: flex-start;

      .back-button {
        align-self: flex-end;
      }
    }

    .records-card {
      margin-bottom: 24px;
    }

    // 详细统计区域移动端适配
    .statistics-section {
      margin-top: 32px;
      padding: 24px 0;

      .ancient-title {
        font-size: 22px;
        margin-bottom: 32px;
      }

      .impact-overview {
        margin-bottom: 32px;
      }

      .impact-card {
        height: 120px;
        padding: 24px 16px;

        :deep(.ant-statistic) {
          .ant-statistic-title {
            font-size: 14px;
          }
        }

        .impact-description {
          font-size: 11px;
        }
      }

      .statistics-tables {
        margin-bottom: 24px;
      }

      .stats-table-card {
        height: 400px;
        margin-bottom: 16px;

        :deep(.ant-card-head) {
          .ant-card-head-title {
            font-size: 16px;
          }
        }
      }
    }
  }
}
</style>
